#include "calServer.hpp"

#include <memory>

void Usage(string proc)
{
    cout << "Usage:\n\t" << proc << " server_port" << endl;
}

void cal(const Request& req, Response* res)
{
    int exitcode = 0, result = 0;
    switch(req._op)
    {
    case '+':
        result = req._x + req._y;
        break;
    case '-':
        result = req._x - req._y;
        break;
    case '*':
        result = req._x * req._y;
        break;
    case '/':
    {
        if (req._y == 0)
        {
            exitcode = 1;
            break;
        }
        result = req._x / req._y;
        break;
    }
    case '%':
    {
        if (req._y == 0)
        {
            exitcode = 2;
            break;
        }
        result = req._x % req._y;
        break;
    }
    default:
        exitcode = 3;
        break;
    }
    res->_exitcode = exitcode;
    res->_result = result;
}

int main(int argc, char* argv[])
{
    if (argc != 2)
    {
        Usage(argv[0]);
        exit(USAGE_ERR);
    }
    uint16_t port = atoi(argv[1]);
    unique_ptr<calServer> svr(new calServer(port));
    svr->initServer();
    svr->startServer(cal);
    return 0;
}